/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.aop.service.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.aop.domain.BisLog;
import me.zhengjie.aop.repository.BisLogRepository;
import me.zhengjie.aop.service.BisLogService;
import me.zhengjie.aop.service.dto.BisLogQueryCriteria;
import me.zhengjie.aop.service.mapstruct.BisLogMapper;
import me.zhengjie.business.domain.Zhsq;
import me.zhengjie.utils.*;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

/**
 * @author Zheng Jie
 * @date 2018-11-24
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BisLogServiceImpl implements BisLogService {

    private final BisLogRepository bisLogRepository;
    private final BisLogMapper bisLogMapper;

    ThreadLocal<Long> currentTime = new ThreadLocal<>();

    @Override
    public Object queryAll(BisLogQueryCriteria criteria, Pageable pageable) {
        log.info("LogServiceImpl queryAll criteria : {}", criteria);
        log.info("LogServiceImpl queryAll pageable : {}", pageable);
        Page<BisLog> page = bisLogRepository.findAll(((root, criteriaQuery, cb) -> QueryHelp.getPredicate(root, criteria, cb)), pageable);
        return page;
    }

    @Override
    public List<BisLog> queryAll(BisLogQueryCriteria criteria) {
        return bisLogRepository.findAll(((root, criteriaQuery, cb) -> QueryHelp.getPredicate(root, criteria, cb)));
    }

    @Override
    public Object queryAllByUser(BisLogQueryCriteria criteria, Pageable pageable) {
        Page<BisLog> page = bisLogRepository.findAll(((root, criteriaQuery, cb) -> QueryHelp.getPredicate(root, criteria, cb)), pageable);
        return PageUtil.toPage(page.map(bisLogMapper::toDto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(String username, String browser, String ip, ProceedingJoinPoint joinPoint, BisLog log) {
        if (log == null) {
            throw new IllegalArgumentException("Log 不能为 null!");
        }
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        me.zhengjie.aop.annotation.BisLog aopLog = method.getAnnotation(me.zhengjie.aop.annotation.BisLog.class);

        String params = getParameter(method, joinPoint.getArgs());
        params = params.replaceAll("\\[", "");
        params = params.replaceAll("\\]", "");
        params = params.replaceAll(" ", "");
        System.out.println("--------------"+params);

        if(params.indexOf(",") == -1) {
            Long zhid = Long.valueOf(params);
            Zhsq zhsq = new Zhsq();
            zhsq.setBisZhsqId(zhid);
            // 方法路径
            String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";
            // 描述
            log.setBisLogDesc(aopLog.value());
            log.setZhsq(zhsq);
            log.setBisLogIp(ip);
            log.setBisLogAddress(StringUtils.getCityInfo(log.getBisLogIp()));
            log.setBisLogMethod(methodName);
            log.setBisLogUsername(username);
            log.setBisLogParams("");
            log.setBisLogBrowser(browser);
            bisLogRepository.save(log);
        } else {
            String[] ids = params.split(",");
            for (String id : ids) {
                System.out.println(id);
                BisLog bisLog = new BisLog();
                Long zhid = Long.valueOf(id);
                Zhsq zhsq = new Zhsq();
                zhsq.setBisZhsqId(zhid);
                // 方法路径
                String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";
                // 描述
                bisLog.setBisLogDesc(aopLog.value());
                bisLog.setBisLogType("INFO");
                bisLog.setZhsq(zhsq);
                bisLog.setBisLogIp(ip);
                bisLog.setBisLogAddress(StringUtils.getCityInfo(bisLog.getBisLogIp()));
                bisLog.setBisLogMethod(methodName);
                bisLog.setBisLogUsername(username);
                bisLog.setBisLogParams("");
                bisLog.setBisLogBrowser(browser);
                bisLogRepository.save(bisLog);
            }
        }

/*
        String sss1 = params.substring(params.indexOf("bisZhsqId"));
        String sss2 = sss1.substring(0, sss1.indexOf(","));
        System.out.println("--------------"+sss2.substring(sss2.indexOf("=")+1));
        Long zhid = Long.valueOf(sss2.substring(sss2.indexOf("=")+1));
        Long zhid = Long.valueOf(sss2.substring(sss2.indexOf("=")+1));*/

    }

    @Override
    public void save(Long zhid, String logDesc, String methodName, HttpServletRequest request) {
        currentTime.set(System.currentTimeMillis());
        BisLog bisLog = new BisLog("INFO",System.currentTimeMillis() - currentTime.get());
        currentTime.remove();

        Zhsq zhsq = new Zhsq();
        zhsq.setBisZhsqId(zhid);
        // 描述
        bisLog.setBisLogDesc(logDesc);
        bisLog.setZhsq(zhsq);
        bisLog.setBisLogIp(StringUtils.getIp(request));
        bisLog.setBisLogAddress(StringUtils.getCityInfo(bisLog.getBisLogIp()));
        bisLog.setBisLogMethod(methodName);
        bisLog.setBisLogUsername(""+SecurityUtils.getCurrentUserId());
        bisLog.setBisLogParams("");
        bisLog.setBisLogBrowser(StringUtils.getBrowser(request));
        bisLogRepository.save(bisLog);
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private String getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        String id = null;
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
                String temp = args[i].toString();
                String sss1 = temp.substring(temp.indexOf("bisZhsqId"));
                String sss2 = sss1.substring(0, sss1.indexOf(","));
                Long zhid = Long.valueOf(sss2.substring(sss2.indexOf("=")+1));
                id = sss2.substring(sss2.indexOf("=")+1);
                break;
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>(4);
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);

                System.out.println(key+"---------"+args[i]);
                if("selectedZhids[]".equals(key)) {
                    id = args[i].toString();
                    break;
                }
            }
        }
        if (argList.isEmpty()) {
            return "";
        }
     //   return argList.size() == 1 ? JSONUtil.toJsonStr(argList.get(0)) : JSONUtil.toJsonStr(argList);
        return id;
    }

    @Override
    public Object findByErrDetail(Long id) {
        BisLog log = bisLogRepository.findById(id).orElseGet(BisLog::new);
        ValidationUtil.isNull(log.getBisLogId(), "BisLog", "id", id);
        byte[] details = log.getBisLogExceptionDetail();
        return Dict.create().set("exception", new String(ObjectUtil.isNotNull(details) ? details : "".getBytes()));
    }

    @Override
    public void download(List<BisLog> logs, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (BisLog log : logs) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("用户名", log.getBisLogUsername());
            map.put("IP", log.getBisLogIp());
            map.put("IP来源", log.getBisLogAddress());
            map.put("描述", log.getBisLogDesc());
            map.put("浏览器", log.getBisLogBrowser());
            map.put("请求耗时/毫秒", log.getBisLogTime());
            map.put("异常详情", new String(ObjectUtil.isNotNull(log.getBisLogExceptionDetail()) ? log.getBisLogExceptionDetail() : "".getBytes()));
            map.put("创建日期", log.getBisLogCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

}
